home *** CD-ROM | disk | FTP | other *** search
/ isnet Internet / Isnet Internet CD.iso / prog / hiz / 09 / 09.exe / adynware.exe / perl / lib / site / URI / Escape.pm next >
Encoding:
Perl POD Document  |  1999-12-28  |  2.0 KB  |  83 lines

  1.  
  2. package URI::Escape;
  3.  
  4. =head1 NAME
  5.  
  6. uri_escape - Escape unsafe characters
  7.  
  8. uri_unescape - Unescape escaped characters
  9.  
  10. =head1 SYNOPSIS
  11.  
  12.  use URI::Escape;
  13.  $safe = uri_escape("10% is enough\n");
  14.  $verysafe = uri_escape("foo", "\0-\377");
  15.  $str  = uri_unescape($safe);
  16.  
  17. =head1 DESCRIPTION
  18.  
  19. This module provide functions to escape and unescape URI strings.
  20. Some characters are regarded as "unsafe" and must be escaped in
  21. accordance with RFC 1738.  Escaped characters are represented by a
  22. triplet consisting of the character "%" followed by two hexadecimal
  23. digits.
  24.  
  25. The uri_escape() function takes an optional second argument that
  26. overrides the set of characters that are to be escaped.  The set is
  27. specified as a string that can be used in a regular expression
  28. character class (between [ ]).  E.g.:
  29.  
  30.   \x00-\x1f\x7f-\xff          # all control and hi-bit characters
  31.   a-z                         # all lower case characters
  32.   ^A-Za-z                     # everything not a letter
  33.  
  34. The default set of characters to be escaped is:
  35.  
  36.   \x00-\x20"#%;<>?{}|\\\\^~`\[\]\x7F-\xFF
  37.  
  38. The module can also export the %escapes hash which contains the
  39. mapping from all characters to the corresponding escape code.
  40.  
  41. =head1 SEE ALSO
  42.  
  43. L<URI::URL>
  44.  
  45. =cut
  46.  
  47. require Exporter;
  48. @ISA = qw(Exporter);
  49. @EXPORT = qw(uri_escape uri_unescape);
  50. @EXPORT_OK = qw(%escapes);
  51.  
  52. use Carp ();
  53.  
  54. for (0..255) {
  55.     $escapes{chr($_)} = sprintf("%%%02X", $_);
  56. }
  57.  
  58. sub uri_escape
  59. {
  60.     my($text, $patn) = @_;
  61.     return undef unless defined $text;
  62.     if (defined $patn){
  63.     unless (exists  $subst{$patn}) {
  64.         $subst{$patn} =
  65.           eval "sub {\$_[0] =~ s/([$patn])/\$escapes{\$1}/g; }";
  66.         Carp::croak("uri_escape: $@") if $@;
  67.     }
  68.     &{$subst{$patn}}($text);
  69.     } else {
  70.     $text =~ s/([\x00-\x20"#%;<>?{}|\\\\^~`\[\]\x7F-\xFF])/$escapes{$1}/g; #"
  71.     }
  72.     $text;
  73. }
  74.  
  75. sub uri_unescape
  76. {
  77.     my @copy = @_;
  78.     for (@copy) { s/%([\dA-Fa-f]{2})/chr(hex($1))/eg; }
  79.     wantarray ? @copy : $copy[0];
  80. }
  81.  
  82. 1;
  83.